<?php

/*
	Class: Config

	About: Author
		J William McCarthy

	About: License
		<http://communit.as/docs/license>

	About: See Also
	 	<App_Db_Table_Abstract>
*/
class Config extends App_Db_Table_Abstract {
    protected $_name 	= 'default_config';
    protected $_primary = array('module','ckey');

	/* Group: Has No Methods */
	
	function keyExists($module = "default",$ckey){
		
		$where = $this->getAdapter()->quoteInto("ckey = ?",$ckey);
		$where .= $this->getAdapter()->quoteInto(" and module = ?",$module);
		
		if($this->getCountByWhereClause($where) == 0){
			return false;
		} else {
			return true;
		}
		
	}

	function set($module = "default",$ckey,$value,$is_cached = false){
		
		if(!$this->keyExists($module,$ckey)){
			$data = array(
				"ckey" 		=> $ckey,
				"module"	=> $module,
				"value"		=> $value,				
			);
			
			if($is_cached){
				$data['is_cached'] = 1;
			} else {
				$data['is_cached'] = 0;
			}
			
			parent::insert($data);
		} else {
			
			$where = $this->getAdapter()->quoteInto("ckey = ?",$ckey);
			$where .= $this->getAdapter()->quoteInto(" and module = ?",$module);
			
			$data = array(
				"value"		=> $value,				
			);
			
			if($is_cached){
				$data['is_cached'] = 1;
			} else {
				$data['is_cached'] = 0;
			}
			
			parent::update($data,$where);
		}
	}
	
	
	function cache(){
		$basepath = Zend_Registry::get('basepath');
		$config_cache_file = $basepath."/etc/cached_config.ini";

		if(file_exists($config_cache_file)){
			unlink($config_cache_file);
		}		

		if(!file_exists($config_cache_file)){
			
			$cacheable = $this->fetchAll('is_cached = 1');
			$config_cache = array();
			if(count($cacheable) > 0){
				foreach($cacheable as $config_item){
					$config_cache[$config_item->module.".".$config_item->ckey ] = $config_item->value;
				}
				
			}
			
			$comment = "THIS FILE IS AUTO-GENERATED. DO NOT EDIT THIS FILE DIRECTLY. YOUR CHANGES WILL BE OVERWRITTEN.";
			
			$config_cache_string = App_ConfigFile::makeSection("cached", "Cached Config", $comment, $config_cache);
			file_put_contents($config_cache_file,$config_cache_string);
			
			/*
			
			$config_cache = array(
				'theme' => Zend_Registry::get('theme'),
				'basepath' => Zend_Registry::get('basepath'),
				'default_profile_fullimage_url' => App_Registry::get('default_profile_fullimage_url',null),
				'upload_path'  => Zend_Registry::get('upload_path',Zend_Registry::get('basepath')),
				'missing_image' => App_Registry::get('missing_image',"/themes/".Zend_Registry::get('theme')."/images/image-missing.png"),
			);
			$config_cache_string = null;
			foreach($config_cache as $key => $val){
				$config_cache_string .= $key. " = " .$val ."\n";		
			}
			*/
				
		}
		
	}
	
}
